﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;

using DevExpress.XtraEditors;
using MINERP.DAL;
using MINERP.ComControls;
using MINERP.BLL.UserLogin;
using MINERP.COM;
using System.Net;
using System.Net.Sockets;
using System.Xml;
using System.Diagnostics;
using System.IO;
using System.Collections;
using MINERP.MODEL.EM;
using MINERP.BLL.Statistics;
using MINERP.Statistics;
using MINERP.MODEL.FoundationModel;

namespace MINERP.UserLogin 
{
    public partial class FrmMain :Form
    {
        #region //private fields

        private users                               _user = null;
        private SimpleButton[]                      _btnArray = null;
        private List<tb_Power>                      _powerList = null;
        private UserLoginBLL                        _userLoginBLL = new UserLoginBLL();
        private List<string>                        _controlName = new List<string>();//受限制的控件名称，权限控制
        private Dictionary<int, string>             _techNames = new Dictionary<int, string>();//此用户能操作的结点ID与节点所对应的界面NAME的KEY VALUE对
        private string                              _assemblyName = string.Empty;
        private string                              _className = string.Empty;
        private string                              _headPicPath = string.Empty;
        private WorkShop_Info                       _workShopInfo =null;//车间信息
        private int i = 0;

        private static FrmMain                      _instance =null;

        private static FrmParent                    _frmMain = null;

        //已经打开的程序集名称
        private List<string>                        _listExistsAssembly = new List<string>();

        #endregion

        private FrmMain()
        {
            InitializeComponent();
        }

        public static string LoginName { set; get; }
        public static string PWD { set; get; }
        //
        private bool _isRestart = false;

        public static FrmMain GetInstance
        {
            get
            {
                if (_instance == null)
                {
                    _instance =  new FrmMain();
                }

                return _instance;
            }
        }

        /// <summary>
        /// 把数据库中所有角色创建成按钮
        /// </summary>
        private void CreateBtnOfAllPower()
        {
            _powerList = new List<tb_Power>();
            _powerList = _userLoginBLL.GetPowerList();
            _btnArray = new SimpleButton[_powerList.Count];

            //int x = this.Width / 10;
            //int y = this.Height / 4;
            int x = (this.Width - 812) / 6;//880
            //按钮距离边框的距离


            //int y = this.Height / 4;
            int y = this.Height / 14;
            int hold = y;

            //定位窗体上的按钮位置
            for (i = 0; i < _btnArray.Length; i++)
            {
                _btnArray[i] = new SimpleButton();
                _btnArray[i].Size = new Size(128, 155);
                _btnArray[i].Enabled = false;
                _btnArray[i].Name = _powerList[i].FrmName;

                if (i == 0)
                {
                    _btnArray[i].Location = new Point(x, y);
                }
                else
                {                   
                    y += _btnArray[i - 1].Height + 20;

                    if (y >= this.Height - hold-30)
                    {
                        y = hold;
                        x = x + _btnArray[i - 1].Width + 30;
                    }

                    _btnArray[i].Location = new Point(x, y);
                }

                string imageFile = Application.StartupPath + "\\imgs\\" + _powerList[i].Name + ".png";

                if (File.Exists(imageFile))
                {
                    _btnArray[i].Image = Image.FromFile(imageFile);
                    _btnArray[i].ImageLocation = ImageLocation.TopCenter;
                }

                _btnArray[i].Text = _powerList[i].Name;
                Font font = new Font("宋体", 13, FontStyle.Bold);
                _btnArray[i].Font = font;

                _btnArray[i].Tag = _powerList[i].AssemblyName;
                _btnArray[i].Click += new System.EventHandler(this.OnClick);
                this.Controls.Add(_btnArray[i]);

                _btnArray[i].BringToFront();
            }
        }

        private void CreateBtnOfAllPower1()
        {
            _powerList = new List<tb_Power>();
            _powerList = _userLoginBLL.GetPowerList();
            _btnArray = new SimpleButton[_powerList.Count];

            //int x = this.Width / 10;
            //int y = this.Height / 4;
            int x = (this.Width - 812) / 2;//880
            //按钮距离边框的距离
            int hold = x;

            //int y = this.Height / 4;
            int y = this.Height / 5;

            //定位窗体上的按钮位置
            for (i = 0; i < _btnArray.Length; i++)
            {
                _btnArray[i] = new SimpleButton();
                _btnArray[i].Size = new Size(128, 155);
                _btnArray[i].Enabled = false;
                _btnArray[i].Name = _powerList[i].FrmName;

                if (i == 0)
                {
                    _btnArray[i].Location = new Point(x, y);
                }
                else
                {
                    x += _btnArray[i - 1].Width + 100;

                    if (x >= this.Width - hold)
                    {
                        x = hold;
                        y = y + _btnArray[i - 1].Height + 30;
                    }

                    _btnArray[i].Location = new Point(x, y);
                }

                string imageFile = Application.StartupPath + "\\imgs\\" + _powerList[i].Name + ".png";

                if (File.Exists(imageFile))
                {
                    _btnArray[i].Image = Image.FromFile(imageFile);
                    _btnArray[i].ImageLocation = ImageLocation.TopCenter;
                }

                _btnArray[i].Text = _powerList[i].Name;
                Font font = new Font("宋体", 13, FontStyle.Bold);
                _btnArray[i].Font = font;

                _btnArray[i].Tag = _powerList[i].AssemblyName;
                _btnArray[i].Click += new System.EventHandler(this.OnClick);
                this.Controls.Add(_btnArray[i]);

                _btnArray[i].BringToFront();
            }
        }

        /// <summary>
        /// 创建所有的用户flash角色按钮
        /// </summary>
        //private void CreateBtnUserRoles()
        //{
        //    _powerList = new List<tb_Power>();
        //    //得到数据库中所有的角色
        //    _powerList = _userLoginBLL.GetPowerList();

        //    _userLoginBLL.UserLogin(LoginName, PWD, out _controlName, out _techNames, out _user);

        //    foreach (tb_Power power in _powerList)
        //    {
        //        //默认按钮不可用
        //        this.axShockwaveFlash1.SetVariable("isUse", "0");
        //        foreach (tb_Power userPower in _user.tb_Power)
        //        {
        //            if (userPower.FrmName == power.FrmName)
        //            {
        //                //如果用户有这个角色，则这个角色的按钮可用
        //                this.axShockwaveFlash1.SetVariable("isUse", "1");
        //            }
        //        }
        //        callFunction("AddButton", power.Name);
        //    }
        //}
        private Dictionary<int, string> techlist;
        private void FrmMain_Load(object sender, EventArgs e)
        {
            try
            {
                //加载flash动画
                //this.axShockwaveFlash1.Movie = Application.StartupPath + "\\UserRoles.swf";
                //this.axShockwaveFlash1.Menu = false;

                CreateBtnOfAllPower(); 
                
                this.pictureBox1.Image =  Image.FromFile(Application.StartupPath + "\\imgs\\background.jpg");

                //把当前用户所拥有的角色按钮激活
                // CreateBtnUserRoles();
                _userLoginBLL.UserLogin(LoginName, PWD, out _controlName, out _techNames, out _user);

                //if (_techNames.Count<1)
                //{
                //    MessageBox.Show("请为用户设定操作节点!");
                //    Application.Exit();
                //    return;
                //}
                techlist = _userLoginBLL.GetMuliRole(_user.userID);

                FrmParent.ControlsName = _controlName;
                //把用户设置为在线状态
                _userLoginBLL.ChangeUserIsOnLine(_user, true);

                foreach (tb_Power power in _user.tb_Power)
                {
                    foreach (SimpleButton btn in _btnArray)
                    {
                        if (btn.Name == power.FrmName && power.Name == btn.Text)
                        {
                            btn.BackColor = Color.DodgerBlue;
                            btn.Enabled = true;
                        }
                    }
                }
                this.notifyMain.Visible = true;
                //加载用户角色

                //AlarmMessageBLL alarmBLL = new AlarmMessageBLL();
                //if (alarmBLL.HaveAlarmMessage(_user.userID))
                //{
                //    FrmAlarmMessage frm = FrmAlarmMessage.GetInstance;
                //    frm.UserId = _user.userID;
                //    frm.OnlyShowNoRead = true;
                //    frm.ShowDialog();
                //}
                GetBalanceAlarmMsg();

                //留言消息检测
                UsersInfo userInfo = new UsersInfo();
                userInfo.Id =_user.userID;
                userInfo.LoginPwd =_user.LoginPwd;
                userInfo.NickName =_user.UserName;
                userInfo.FacePath = _user.HeadPicPath;
                AppSetter.CurrentUser = userInfo;

                timer2.Enabled = true;
                BalanceCheckTimer.Enabled = true;
                _workShopInfo = _userLoginBLL.GetWorkShopInfo();
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message, "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
        }

        AlarmMessageBLL alarmBLL = new AlarmMessageBLL();
        /// <summary>
        /// 得到是否有财务警告信息
        /// </summary>
        public void GetBalanceAlarmMsg()
        {

            //AlarmMessageBLL alarmBLL = new AlarmMessageBLL();
            if (alarmBLL.HaveAlarmMessage(_user.userID))
            {
                FrmAlarmMessage frm = FrmAlarmMessage.GetInstance;
                frm.UserId = _user.userID;
                frm.OnlyShowNoRead = true;
                frm.Visible = false;
                frm.ShowDialog();
            }
        }

        void Application_ApplicationExit(object sender, EventArgs e)
        {
            if (_isRestart)
            {
                Process.Start(Application.ExecutablePath);
            }
        }

        #region //flash处理

        //private void callFunction(string funName, string arg)
        //{
        //    //C#传给Flash的值
        //    axShockwaveFlash1.CallFunction("<invoke name=\"" + funName + "\" returntype=\"xml\"><arguments><string>" + arg + "</string></arguments></invoke>");
        //}
        
        #endregion

        private void OnClick(object sender, EventArgs e)
        {
            try
            {
                //是不是一样的用户角色
                bool isOpen = false;
                this.Cursor = Cursors.WaitCursor;
                string className = ((SimpleButton)sender).Name;//Button名称即窗体名称（之前给Button赋值为窗体名）
                string assemblyName = ((SimpleButton)sender).Tag.ToString();

                if (this._listExistsAssembly.Contains(assemblyName))
                {
                    isOpen = true;
                }

                if (isOpen)
                {
                    if (_frmMain.IsDisposed || assemblyName == "MINERP.PrintManage")
                    {                                      
                        _frmMain = (FrmParent)Assembly.Load(assemblyName).CreateInstance(className);

                        //FrmParent.ControlsName = _controlName;
                        _frmMain.userId = _user.userID;
                        _frmMain.userName = _user.UserName;
                        _frmMain.operates = _techNames;
                        _frmMain.GroupId = _user.tb_WorkerGroup.GroupId;
                        _frmMain.HeadPicPath = _headPicPath;
                        _frmMain.isShowMenuForm = true;
                        _frmMain.workShopInfo = _workShopInfo;
                    }
                    this.Hide();
                    KeyValuePair<int, string> pair = this._techNames.FirstOrDefault(t => t.Value == className);

                    if (pair.Value != null)
                    {
                        _frmMain.CurrentTechID = pair.Key;
                    }
                    _frmMain.Show();
                    this.Cursor = Cursors.Default;
                    return;
                }
                //Stopwatch sw = new Stopwatch();
                //sw.Start();

                _frmMain = (FrmParent)Assembly.Load(assemblyName).CreateInstance(className);
                //sw.Stop();
                //MessageBox.Show(sw.ElapsedMilliseconds.ToString());
                //FrmParent.ControlsName = _controlName;
                _frmMain.userId = _user.userID;
                _frmMain.userName = _user.UserName;
                _frmMain.GroupName = _user.tb_WorkerGroup.GroupName;
               
                _frmMain.GroupId = _user.tb_WorkerGroup.GroupId;
                _frmMain.HeadPicPath = _headPicPath;
                _frmMain.isShowMenuForm = true;
                _frmMain.workShopInfo = _workShopInfo;

                KeyValuePair<int, string> pair1 = this._techNames.FirstOrDefault(t => t.Value == className);
             
                if (pair1.Value != null)
                {
                    _frmMain.CurrentTechID = pair1.Key;
                }
                else
                {
                    //this.Cursor = Cursors.Default;
                    //MessageBox.Show("没有为用户设定可操作节点，请先设定再登陆");
                    //_frmMain.Close();
                    //return;
                }

                if (techlist == null)
                {
                    _frmMain.operates = _techNames;
                }
                else
                {
                    _frmMain.operates = techlist;//获取多角色节点
                }
                //_frmMain.InitiAuthority();

                this.Hide();

                //记录登录的窗体的程序集
                if (!this._listExistsAssembly.Contains(assemblyName))
                {
                    this._listExistsAssembly.Add(assemblyName);
                }
                //绑定删除程序集名称
                _frmMain.FormClosed += new FormClosedEventHandler(_frmMain_FormClosed);
                _frmMain.Show();


                this.Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                this.Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
        }

        private void _frmMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            string name = sender.GetType().Assembly.FullName;
            name = name.Substring(0, name.IndexOf(","));
            this._listExistsAssembly.Remove(name);
        }

        #region //任务栏显示

        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason != CloseReason.UserClosing)
            {
                e.Cancel = true;
                this.Hide();
            }
            else
            {
                _instance = null;
            }
        }

        
        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            this.Visible = true;
        }

        private void notifyMain_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.Visible = !this.Visible;
        }

        private void ExitItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(this, "您真的要退出系统吗？", "系统询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                notifyMain.Visible = false;
                //变为离线状态
                _userLoginBLL.ChangeUserIsOnLine(_user, false);
                Logoff.ResetPrinter();
                System.Environment.Exit(-1);
            }
        }

        #endregion

        #region //定时检测程序

        /// <summary>
        /// udp 获取广播信息
        /// </summary>
        /// <returns></returns>
        private void GetServerInfo()
        {
            int recv = 0;
            byte[] data = new byte[1024];

            //构建TCP 服务器

            //得到本机IP，设置TCP端口号         
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 8001);
            Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            newsock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 5000);
            //绑定网络地址
            newsock.Bind(ipep);
            //得到客户机IP
            IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
            EndPoint Remote = (EndPoint)(sender);
            DateTime nowTime = DateTime.Now;

            try
            {
                recv = newsock.ReceiveFrom(data, ref Remote);
            }
            catch
            {
                timer1.Enabled = false;
                MessageBox.Show("与服务器的连接已中断,请与管理员联系", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                newsock.Close();
                //变为离线状态
                this._user.IsOnline = false;
                _userLoginBLL.Save();
                System.Environment.Exit(-1);
            }

            newsock.Close();

        }

        /// <summary>
        /// 定时检测服务器连接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {
            GetServerInfo();
        }

        #endregion

        /// <summary>
        /// 处理flash按钮的点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //private void axShockwaveFlash1_FSCommand(object sender, AxShockwaveFlashObjects._IShockwaveFlashEvents_FSCommandEvent e)
        //{
        //    //得到按钮角色的程序集名称和窗体名称
        //    string assemblyName = string.Empty;
        //    string frmName = string.Empty;

        //    foreach (tb_Power power in _user.tb_Power)
        //    {
        //        if (power.Name == e.command)
        //        {
        //            assemblyName = power.AssemblyName;
        //            frmName = power.FrmName;
        //        }
        //    }

        //    if (string.Compare(string.Empty, assemblyName) != 0)
        //    {
        //        FrmParent frmparent = (FrmParent)Assembly.Load(assemblyName).CreateInstance(frmName);
        //        frmparent.ControlsName = _controlName;
        //        frmparent.userId = _user.userID;
        //        frmparent.userName = _user.LoginName;
        //        frmparent.operates = _techNames;
        //        frmparent.GroupId = _user.tb_WorkerGroup.GroupId;
        //        frmparent.HeadPicPath = _headPicPath;
        //        frmparent.InitiAuthority();
        //        this.Hide();

        //        frmparent.Show();
        //    }
        //}

        private void btnExit_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(this, "您真的要退出系统吗？", "系统询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                notifyMain.Visible = false;
                //变为离线状态
                _userLoginBLL.ChangeUserIsOnLine(_user, false);
                Logoff.ResetPrinter();
                System.Environment.Exit(-1);
            }
        }

        private void btnReload_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(this, "确定要注销系统吗？", "系统询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                
                _isRestart = true;
                //变为离线状态
                _userLoginBLL.ChangeUserIsOnLine(_user, false);
                int isHaveFrm = (int)UtilMethod.FindWindow(null, "登录");
                if (isHaveFrm > 0)
                {
                    UtilMethod.SetWindowPos(isHaveFrm, -2, Screen.PrimaryScreen.WorkingArea.Width / 2 - 229, Screen.PrimaryScreen.WorkingArea.Height / 2 - 134, 458, 269, 0x40);//激活登录窗体
                    Logoff.ResetPrinter();
                    this.Close();
                    CloseAllChildForms();
                }

            }

        }
        private void CloseAllChildForms()
        {
            FormCollection formCollection = Application.OpenForms;
            List<IntPtr> formHandles = new List<IntPtr>();
            foreach (Form item in formCollection)
            {
                if (item.Name != "FrmLogin")
                {
                    formHandles.Add(item.Handle);
                }
            }
            foreach (IntPtr handle in formHandles)
            {
                try
                {
                    Form.FromHandle(handle).Dispose();
                }
                catch (Exception)
                {
                    
                   
                }
              
            }
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {

        }

        private void pictureBox1_Click_1(object sender, EventArgs e)
        {

        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            try
            {
                frmMain frm = frmMain.GetInstance(_user.userID);
                frm.GetMessages();
            }
            catch { }
        }

        private void BalanceCheckTimer_Tick(object sender, EventArgs e)
        {
            GetBalanceAlarmMsg();
        }
    }
}
